//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/select/select_title_widget.dart';
import 'package:hktk_app/widget/show_label_widget.dart';



/// 保存saveCategoryModels，saveSelectCategoryId，dataModel
/// 选择科目页面
class SelectSubjectPage extends StatefulWidget {
  /// 选择的考试id
  final List<CategoryModel> subjectList;

  /// 需要返回的页面
  final Widget? onPage;

  /// 已购买的科目
  final List<CategoryModel>? buyCategorys;

  /// 是否跳转首页
  final int pageIndex;
  final String pageName;
  final Map<String,dynamic>? arguments;


  const SelectSubjectPage({
    super.key,
    required this.subjectList,
    this.onPage,
    this.buyCategorys,
    this.pageIndex = 0,
    this.pageName="/tab",
    this.arguments,
  });

  @override
  State<SelectSubjectPage> createState() => _SelectSubjectPageState();
}

class _SelectSubjectPageState extends State<SelectSubjectPage> {
  late BuildContext _context;

  /// 搜索关键字
  late String _searchKey;

  /// 对应数据
  late List<CategoryModel> _list;

  /// 购买的id
  late List<int> _buyIds;

  @override
  void initState() {
    super.initState();

    _searchKey = "";
    _list = widget.subjectList;
    _buyIds = [];
    if (widget.buyCategorys != null) {
      _buyIds = widget.buyCategorys!
          .map((CategoryModel model) => model.id ?? 0)
          .toList();
    }
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    // 获取安全边距

    return Scaffold(
      backgroundColor: colorWhite1,
      body: Container(
        padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight, bottom: ScreenUtil().bottomBarHeight),
        child: Column(
          children: [
            SelectTitleWidget(
                pageContext: context,
                titleName: "选择科目",
                onSubmittedFun: _searchSubject),
            Expanded(child: _contents()),
          ],
        ),
      ),
    );
  }

  /// 内容显示方法
  _contents() {

    double width = ScreenUtil().screenWidth;
    double sizeHeight = ScreenUtil().screenHeight;
    double height = sizeHeight -ScreenUtil().statusBarHeight - ScreenUtil().bottomBarHeight - 88;
    return MediaQuery.removePadding(
      removeTop: true,
      context: _context,
      child: SingleChildScrollView(
        child: SizedBox(
          width: width,
          height: height,
          child: Stack(
            children: [
              _content(),
              Positioned(
                bottom:  ScreenUtil().bottomBarHeight + 50,
                child: _button(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择科目搜索方法
  _searchSubject(String value) {
    setState(() {
      _searchKey = value;
    });
  }

  /// 选好了按钮
  _button() {

    return SizedBox(
      width: ScreenUtil().screenWidth,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () {
              _buttonOnTap();
            },
            child: Container(
              width: 318,
              // height: 88,
              padding: EdgeInsets.symmetric(vertical: 5),
              decoration: BoxDecoration(
                color: colorBlue1,
                borderRadius: BorderRadius.all(Radius.circular(44)),
              ),
              child: Center(
                child: Text(
                  "选好了",
                  style: FontUtil.fontWhile1(18, fontWeight: FontWeight.w500),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 主体内容
  _content() {
    return Container(
      margin: EdgeInsets.fromLTRB(36, 30, 36, 80),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: [
            _titleShow("我的科目"),
            hiSpace(height: 24),
            _showItems2(type: true, onTapFun: _iconFun),
            hiSpace(height: 24),
            _titleShow("添加科目"),
            hiSpace(height: 24),
            _showItems2(type: false, onTapFun: _onTapFunAdd),
            hiSpace(height: 24),
          ],
        ),
      ),
    );
  }

  /// 标题显示
  _titleShow(String name) {
    return Text(
      name,
      style: FontUtil.fontBlack1(20, fontWeight: FontWeight.w500),
    );
  }

  /// 显示方法
  _showItems2({
    required bool type,
    required ValueChanged<int> onTapFun,
  }) {
    List<Widget> list = [];
    for (int i = 0; i < _list.length; i++) {
      CategoryModel model = _list[i];
      _addItemsList(
        add: _listAdd(model: model, type: type),
        type: type,
        list: list,
        index: i,
        name: model.name!,
        id: model.id,
        onTapFun: onTapFun,
      );
    }
    return Container(
      constraints: BoxConstraints(minHeight: 200),
      child: Wrap(
        spacing: 20,
        runSpacing: 30,
        children: list,
      ),
    );
  }

  /// 添加对应的组件
  _addItemsList({
    required bool add,
    required bool type,
    required List<Widget> list,
    required int index,
    required String name,
    int? id,
    required ValueChanged<int> onTapFun,

  }) {
    if (add) {
      if (type) {
        list.add(ShowLabelWidget.cancel(
          text: name,
          index: index,
          iconFun: onTapFun,
          showBuy: _getShowBuy(id),
          showFlag: false,
        ));
      } else {
        list.add(GestureDetector(
          onTap: () {
            _onTapFunAdd(index);
          },
          child: ShowLabelWidget(

            text: name,
            showBuy: _getShowBuy(id),
          ),
        ));
      }
    }
  }

  /// 计算是否添加组件方法
  _listAdd({
    required CategoryModel model,
    required bool type,
  }) {
    if (model.isSelect! == type) {
      if (_searchKey != "") {
        return model.name!.contains(_searchKey);
      } else {
        return true;
      }
    }
    return false;
  }

  /// 计算是否显示购买标签
  _getShowBuy(int? id) {
    if (widget.buyCategorys == null) {
      return false;
    }
    return _buyIds.contains(id);
  }

  /// 取消按钮点击方法
  _iconFun(int index) {
    setState(() {
      _list[index].isSelect = false;
    });
  }

  /// 点击方法
  _onTapFunAdd(int i) {
    setState(() {
      _list[i].isSelect = true;
    });
  }

  /// 选好了按钮点击方法
  void _buttonOnTap() {
    // 判断是否选中数据
    List<CategoryModel> selList = MyUtil.getSelList(_list);
    if (selList.isEmpty) {
      // 没有选中数据
      ToastUtil.show(context: _context, msg: "请至少选择一个科目");
      return;
    }



    // 将数据储存
    IndustryDao.saveCategoryModels(_list);
    IndustryDao.saveSelectCategoryId(0);


    // data_model也需要保存
    dataUtilComm.dataModel.categoryId = _list[0].id! ;

    // 发生数据到后端
    try {
      IndustryDao.settingChoose(subjectList: selList);
    } catch (e) {
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    }
    if (widget.onPage == null) {
      // 跳转回首页
      Navigator.pushNamed(_context, "/tab");

    } else {
      // 跳转至对应页面
      Navigator.pushNamedAndRemoveUntil(_context, widget.pageName, (route){
        return route.settings.name == "/tab"||route.settings.name == "/";
      },arguments: widget.arguments);
    }
  }
}
